package com.jstyle.jclife.activity;

import android.Manifest;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.support.constraint.ConstraintSet;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.CoordinateConverter;
import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.baoyz.widget.PullRefreshLayout;
import com.jstyle.blesdk.cmdenum.SendCmdState;
import com.jstyle.blesdk.constant.DeviceKey;
import com.jstyle.blesdk.model.DeviceBean;
import com.jstyle.blesdk.model.GetData;
import com.jstyle.jclife.R;
import com.jstyle.jclife.adapter.HistoryDateAdapter;
import com.jstyle.jclife.adapter.RecyclerViewBaseAdapter;
import com.jstyle.jclife.adapter.TrackRecordAdapter;
import com.jstyle.jclife.app.MyApplication;
import com.jstyle.jclife.ble.BleManager;
import com.jstyle.jclife.daoManager.GpsDataDaoManager;
import com.jstyle.jclife.daoManager.PathRecordDaoManager;
import com.jstyle.jclife.minterface.OnScrollToListener;

import com.jstyle.jclife.model.Device1810;
import com.jstyle.jclife.model.GpsData;
import com.jstyle.jclife.model.ItemData;

import com.jstyle.jclife.model.JstyleDevice;
import com.jstyle.jclife.model.PathRecord;
import com.jstyle.jclife.model.UploadData;
import com.jstyle.jclife.model.UploadGpsData;
import com.jstyle.jclife.utils.DateUtil;
import com.jstyle.jclife.utils.NetWorkConast;
import com.jstyle.jclife.utils.PermissionsUtil;
import com.jstyle.jclife.utils.SchedulersTransformer;
import com.jstyle.jclife.utils.ScreenUtils;
import com.jstyle.jclife.utils.SharedPreferenceUtils;
import com.jstyle.jclife.utils.UploadUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class ExerciseRecordListActivity extends BaseActivity implements RecyclerViewBaseAdapter.OnItemClickListener, PullRefreshLayout.OnRefreshListener, AMapLocationListener, GeocodeSearch.OnGeocodeSearchListener {

    @BindView(R.id.RecyclerView_exercise_Record)
    RecyclerView RecyclerViewExerciseRecord;
    @BindView(R.id.bt_goal_back)
    Button btGoalBack;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_share)
    ImageView ivShare;
    @BindView(R.id.tv_track_totalTime)
    TextView tvTrackTotalTime;

    private HistoryDateAdapter historyDateAdapter;
    private String queryDate;
    private static final String TAG = "ExerciseRecordListActiv";
    private String lastGpsTime;
    private boolean isBefore;
    private TrackRecordAdapter myAdapter;
    @BindView(R.id.tv_refresh_tips)
    TextView tvRefreshTips;
    @BindView(R.id.iv_refresh_tips)
    ImageView ivRefreshTips;
    @BindView(R.id.rl_refresh_tips)
    RelativeLayout rlRefreshTips;
    @BindView(R.id.SwipeRefreshLayout)
    PullRefreshLayout SwipeRefreshLayout;
    public static boolean needAutoSyc = true;
    private AMapLocationClient aMapLocationClient;
    private boolean isMainLand;
    boolean LocationChanged = false;
    private String address;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exercise_record);
        ButterKnife.bind(this);
        queryDate = DateUtil.getDefaultFormatTime(new Date());
        address = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_ADDRESS);
        if (MyApplication.getJstyleDevice() instanceof Device1810) {
            tvRefreshTips.setVisibility(View.INVISIBLE);
            ivRefreshTips.setVisibility(View.INVISIBLE);
        } else {
            lastGpsTime = GpsDataDaoManager.getLastInsertDataTime();
            Log.i(TAG, "onCreate: "+lastGpsTime);

            initRefreshLayout();
        }
        initLocation();
        init();
    }

    private void initRefreshLayout() {
        Animation operatingAnim = AnimationUtils
                .loadAnimation(this, R.anim.refresh);
        LinearInterpolator lin = new LinearInterpolator();
        operatingAnim.setInterpolator(lin);
        ivRefreshTips.startAnimation(operatingAnim);
        SwipeRefreshLayout.setOnRefreshListener(this);
        if (needAutoSyc && BleManager.getInstance().isConnected()) {
            GetData getData = new GetData();
            sendData(SendCmdState.GET_SPORTMODEL_DATA, getData);
            SwipeRefreshLayout.setRefreshing(true);
            this.onRefresh();
            needAutoSyc = false;
        } else {

        }
    }

    private void init() {
        //  showWeek = DateUtil.getTodayWeek(0);
        btGoalBack.setText(R.string.Workout_History);
        ivShare.setVisibility(View.GONE);
        ScreenUtils.setTitleTypeface(btGoalBack);
        final List<PathRecord> pathRecordList = PathRecordDaoManager.getAllPathRecord();
        int totalTime = 0;
        Map<String, List<PathRecord>> mapPathRecord = new HashMap<>();
        for (PathRecord pathRecord : pathRecordList) {
            String date = pathRecord.getMDate();
            String month = date.substring(0, 5);
            List<PathRecord> list = mapPathRecord.get(month);
            if (list == null) {
                list = new ArrayList<>();
                mapPathRecord.put(month, list);
            }
            list.add(pathRecord);
            totalTime += Integer.parseInt(pathRecord.getMDuration());
        }
        ScreenUtils.setTitleTypeface(tvTrackTotalTime);
        tvTrackTotalTime.setText(DateUtil.getSportTime(totalTime));
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        RecyclerViewExerciseRecord.setLayoutManager(linearLayoutManager);
        RecyclerViewExerciseRecord.getItemAnimator().setAddDuration(100);
        RecyclerViewExerciseRecord.getItemAnimator().setRemoveDuration(100);
        RecyclerViewExerciseRecord.getItemAnimator().setMoveDuration(200);
        RecyclerViewExerciseRecord.getItemAnimator().setChangeDuration(100);
        myAdapter = new TrackRecordAdapter(this);
        RecyclerViewExerciseRecord.setAdapter(myAdapter);
        myAdapter.setOnScrollToListener(new OnScrollToListener() {

            @Override
            public void scrollTo(int position) {
                RecyclerViewExerciseRecord.smoothScrollToPosition(position);
            }
        });
        initDatas(mapPathRecord);
        myAdapter.setMapClickListener(new TrackRecordAdapter.onMapItemClickListener() {
            @Override
            public void onClick(PathRecord pathRecord, LatLng latLng) {
                int mode = pathRecord.getExerciseMode();
                Log.i(TAG, "onClick: " + mode);
                if (mode == 5 || mode == 6 || mode == 7 || mode == 10) return;
                startHistoryActivity(pathRecord, latLng);
            }
        });

    }

    private void initDatas(Map<String, List<PathRecord>> map) {
        List<ItemData> list = new ArrayList<>();
        for (Map.Entry<String, List<PathRecord>> entry : map.entrySet()) {
            ItemData itemData = new ItemData();
            itemData.setUuid(UUID
                    .randomUUID().toString());
            itemData.setmDate(entry.getKey());
            itemData.setPathRecordList(entry.getValue());
            list.add(itemData);
        }
        if (list.size() == 0) return;
        Collections.sort(list);
        ItemData itemData = list.get(0);
        itemData.setExpand(true);
        List<ItemData> children = myAdapter.getChildrenByPath(itemData.getPathRecordList(), itemData.getTreeDepth());
        list.addAll(1, children);
        itemData.setChildren(children);
        myAdapter.addAll(list, 0);
    }

    private void startHistoryActivity(final PathRecord pathRecord, final LatLng latLng) {
        PermissionsUtil.requestPermissions(this, new PermissionsUtil.PermissionListener() {
            @Override
            public void granted(String name) {
                startRecordHistoryActivity(latLng, pathRecord);
            }

            @Override
            public void NeverAskAgain() {

            }

            @Override
            public void disallow(String name) {

            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    }

    String mDate;
    Class historyActivity;

    private void startRecordHistoryActivity(LatLng latLng, PathRecord pathRecord) {
        historyActivity = ExerciseHistoryGoogleActivity.class;
        mDate = pathRecord.getMDate();
        Locale locale = getResources().getConfiguration().locale;
        String country = locale.getCountry();
        if (latLng != null) {

            //返回true代表当前位置在大陆、港澳地区，反之不在。
            boolean isAMapDataAvailable = CoordinateConverter.isAMapDataAvailable(latLng.latitude, latLng.longitude);
            boolean isTransFormer=false;
            if (isAMapDataAvailable) {
                if(LocationChanged){
                    historyActivity = isMainLand?ExerciseHistoryActivity.class:ExerciseHistoryGoogleActivity.class;
                    isTransFormer=!isMainLand;
                }else{
                    historyActivity=ExerciseHistoryActivity.class;
                   // isTransFormer=!country.toLowerCase().equals("cn");
                }
            } else {
                historyActivity = ExerciseHistoryGoogleActivity.class;
                isTransFormer=true;
            }
            toHistoryActivity(isTransFormer);


//            GeocodeSearch geocodeSearch=new GeocodeSearch(this);
//            geocodeSearch.setOnGeocodeSearchListener(this);
//            LatLonPoint latLonPoint=new LatLonPoint(latLng.latitude,latLng.longitude);
//            RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200,GeocodeSearch.AMAP);
//            geocodeSearch.getFromLocationAsyn(query);
        } else {
            historyActivity = ExerciseHistoryActivity.class;
            toHistoryActivity(false);
        }


    }

    @OnClick(R.id.iv_back)
    public void onViewClicked() {
        finish();
    }


    @Override
    public void onItemClick(int position) {
        historyDateAdapter.setSelected(position);
    }

    List<PathRecord> pathRecordList = new ArrayList<>();
    List<GpsData> gpsDataList = new ArrayList<>();
    List<UploadGpsData.DataTotalBean.DataDetailBean> listHealth = new ArrayList<>();
    List<UploadData.DataTotalBean> dataListSportType = new ArrayList<>();
    @Override
    public void dataCallback(DeviceBean deviceBean, SendCmdState sendCmdState) {
        super.dataCallback(deviceBean, sendCmdState);
        switch (sendCmdState) {
            case GET_SPORTMODEL_DATA:
                boolean isFinish = deviceBean.isFinish();
                //  showProgressDialog(getString(R.string.Data_Synchronizing));
                List<Map<String, String>> list = deviceBean.getDataList();
                for (Map<String, String> map : list) {
                    UploadData.DataTotalBean dataTotalBean = new UploadData.DataTotalBean();
                    List<String> listHealth = new ArrayList<>();
                    String date = map.get(DeviceKey.KSportDate);
                    String model = map.get(DeviceKey.KSportModel);
                    String hr = map.get(DeviceKey.KSportHeart);
                    String time = map.get(DeviceKey.KSPortModelTime);
                    String steps = map.get(DeviceKey.KSportSteps);
                    String speed = map.get(DeviceKey.KSportSpeed);
                    String speedSeconds = map.get(DeviceKey.KSportSpeedSeconds);
                    String calories = map.get(DeviceKey.KSportCalories);
                    String distance = map.get(DeviceKey.KSportDistance);
                    PathRecord pathRecord = new PathRecord();
                    pathRecord.setMDate(date);
                    pathRecord.setExerciseMode(Integer.valueOf(model));
                    pathRecord.setCalString(calories);
                    pathRecord.setMDistance(distance);
                    pathRecord.setMAveragespeed(speed);
                    pathRecord.setHeart(hr);
                    pathRecord.setMStep(steps);
                    pathRecord.setMDuration(time);
                    pathRecord.setAddress(address);
                    pathRecordList.add(pathRecord);
                    listHealth.add(model);
                    listHealth.add(hr);
                    listHealth.add(time);
                    listHealth.add(steps);
                    listHealth.add(speedSeconds);
                    listHealth.add(calories);
                    listHealth.add(distance);
                    dataTotalBean.setTime("20" + date);
                    dataTotalBean.setDataDetail(listHealth);
                    dataListSportType.add(dataTotalBean);
                }
                if (isFinish) {
                    UploadData uploadData = UploadUtils.getUploadData(address, NetWorkConast.sportTypeData);
                    uploadData.setDataTotal(dataListSportType);
                    UploadUtils.uploadData(uploadData);
                    saveExerciseMode();
                    if (MyApplication.getJstyleDevice().getDeviceNo().equals(JstyleDevice.device_1755)) {
                        getGpsData(0);
                    } else {
                        disMissProgressDialog();
                        SwipeRefreshLayout.setRefreshing(false);
                        init();
                    }

                }
                break;
            case GET_GPS_DATA:
                boolean isFinishGps = deviceBean.isFinish();
                List<Map<String, String>> listGps = deviceBean.getDataList();
                for (Map<String, String> map : listGps) {
                    String date = map.get(DeviceKey.KLocationTime);
                    isBefore = TextUtils.isEmpty(lastGpsTime) ? true : DateUtil.beforeData(lastGpsTime, date);
                    // isBefore = true ;
                    int id = Integer.parseInt(map.get(DeviceKey.KDataID));
                    String Latitude = map.get(DeviceKey.KLocationLatitude);
                    String Longitude = map.get(DeviceKey.KLocationLongitude);
                    String isStart = map.get(DeviceKey.KIsLocationStart);
                    String[] laStringArrays = Latitude.split(",");
                    String[] loStringArrays = Longitude.split(",");
                    for (int i = 0; i < laStringArrays.length; i++) {
                        UploadGpsData.DataTotalBean.DataDetailBean dataDetailBean = new UploadGpsData.DataTotalBean.DataDetailBean();
                        long startL = DateUtil.getGpsDateLong(date);
                        long endL = startL + i * 1000;
                        String gpsTime = DateUtil.getFormatTimeString(endL);
                        dataDetailBean.setGpsDate("20" + gpsTime);
                        dataDetailBean.setLatitude(laStringArrays[i]);
                        dataDetailBean.setLongitude(loStringArrays[i]);
                        listHealth.add(dataDetailBean);
                    }


                    if ("1".equals(isStart)) {
                        UploadGpsData uploadGpsData = UploadUtils.getUploadGpsData(address);
                        UploadGpsData.DataTotalBean dataTotalBean = new UploadGpsData.DataTotalBean();
                        dataTotalBean.setTime("20" + date);
                        List<UploadGpsData.DataTotalBean.DataDetailBean> listHealthUpload = new ArrayList<>(listHealth);
                        dataTotalBean.setDataDetail(listHealthUpload);
                        List<UploadGpsData.DataTotalBean> dataListGps = new ArrayList<>();
                        dataListGps.add(dataTotalBean);
                        uploadGpsData.setDataTotal(dataListGps);
                        UploadUtils.uploadGpsData(uploadGpsData);
                        listHealth.clear();
                    }
                    GpsData gpsData = new GpsData();
                    gpsData.setDate(date);
                    gpsData.setAddress(address);
                    gpsData.setLatitudeString(Latitude);
                    gpsData.setLongitudeString(Longitude);
                    gpsDataList.add(gpsData);
                    if (id != 0 && id % 149 == 0) {//一次最多150条
                        if (isBefore) {//已经保存了就不同步了
                            getGpsData(2);
                        } else {
                            saveGpsData(gpsDataList);
                            return;
                        }
                    }
                }
                if (isFinishGps) {
                    saveGpsData(gpsDataList);
                }
                break;
        }

    }

    private void saveGpsData(List<GpsData> dataList) {
        Log.i(TAG, "saveGpsData: ");
        final List<GpsData> data = new ArrayList<>();
        data.addAll(dataList);
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                GpsDataDaoManager.insertPathRecord(data);
                e.onComplete();
            }
        }).compose(SchedulersTransformer.<String>applySchedulers()).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {
                Log.i(TAG, "onSubscribe: ");
            }

            @Override
            public void onNext(String value) {
                Log.i(TAG, "onNext: ");
            }

            @Override
            public void onError(Throwable e) {

                Log.i(TAG, "onError: gps save " + e.getLocalizedMessage());
            }

            @Override
            public void onComplete() {
                gpsDataList.clear();
                Log.i(TAG, "onComplete: gps ");
                disMissProgressDialog();
                SwipeRefreshLayout.setRefreshing(false);
                lastGpsTime = GpsDataDaoManager.getLastInsertDataTime();
                init();
            }
        });

    }



    private void getGpsData(int count) {
        GetData getData = new GetData();
        getData.setDataNum(count);
        sendData(SendCmdState.GET_GPS_DATA, getData);

    }

    private void saveExerciseMode() {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                PathRecordDaoManager.insertPathRecord(pathRecordList);
                e.onComplete();
            }
        }).compose(SchedulersTransformer.<String>applySchedulers()).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {
                Log.i(TAG, "onSubscribe: ");
            }

            @Override
            public void onNext(String value) {
                Log.i(TAG, "onNext: ");
            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: mode" + e.getMessage());
            }

            @Override
            public void onComplete() {
                pathRecordList.clear();
            }
        });
    }

    @Override
    public void onRefresh() {
        ivRefreshTips.clearAnimation();
        rlRefreshTips.setVisibility(View.INVISIBLE);
        if (!BleManager.getInstance().isConnected()) {
            SwipeRefreshLayout.setRefreshing(false);
            ScreenUtils.showSetSuccessFul(tvTrackTotalTime, getString(R.string.Bluetooth_Disconnected));
        } else {
            GetData getData = new GetData();
            sendData(SendCmdState.GET_SPORTMODEL_DATA, getData);
        }
    }

    private void initLocation() {
        aMapLocationClient = new AMapLocationClient(this);
        aMapLocationClient.setLocationListener(this);
        AMapLocationClientOption aMapLocationClientOption = new AMapLocationClientOption();
        aMapLocationClientOption.setOnceLocation(true);
        aMapLocationClientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        aMapLocationClient.setLocationOption(aMapLocationClientOption);
        aMapLocationClient.startLocation();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (aMapLocationClient != null) aMapLocationClient.onDestroy();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        Log.i(TAG, "onLocationChanged: "+aMapLocation.getLatitude()+" "+aMapLocation.getLongitude());
        isMainLand = "中国".equals(aMapLocation.getCountry()) && !"1852".equals((aMapLocation.getCityCode()));
        LocationChanged = !TextUtils.isEmpty(aMapLocation.getCountry());

        Log.i(TAG, "onLocationChanged: country " + aMapLocation.getCountry() + " LocationChanged: " + LocationChanged);
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        boolean isTransFormer = false;
        if (i == 1000) {
            if ("1852".equals(regeocodeResult.getRegeocodeAddress().getCityCode())) {//香港澳门
                isTransFormer = true;
            }

        }
        Log.i(TAG, "onRegeocodeSearched: "+regeocodeResult.getRegeocodeAddress().getCityCode());
        //toHistoryActivity(isTransFormer);

    }

    private void toHistoryActivity(boolean isTransFormer) {
        Intent intent = new Intent(this, historyActivity);
        intent.putExtra(ExerciseHistoryActivity.pathRecordDate, mDate);
        intent.putExtra("isTransFormer", isTransFormer);
        startActivity(intent);
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }
}
